package org.az.netty_study.p16_rpc.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.az.netty_study.p16_rpc.message.RpcReqMessage;
import org.az.netty_study.p16_rpc.message.RpcResMessage;
import org.az.netty_study.p16_rpc.service.HelloService;

import java.lang.reflect.Method;

@ChannelHandler.Sharable
public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcReqMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcReqMessage msg)  {
        RpcResMessage res = new RpcResMessage();
        res.setSequenceId(msg.getSequenceId());
        try {
            HelloService service = (HelloService)ServicesFactory.getService(Class.forName(msg.getInterfaceName()));
            Method method = service.getClass().getMethod(msg.getMethodName(), msg.getParamTypes());
            Object result = method.invoke(service, msg.getParamValues());
            res.setReturnValue(result);
        } catch (Exception e) {
            e.printStackTrace();
            res.setExceptionValue("远程调用出错，原因：" + e.getCause().getMessage());
        }
        ctx.writeAndFlush(res);
    }

}
